<?php
namespace addons\TfFutures\backend\controllers;

use addons\TfFutures\common\models\NoticeModel;
use yii\data\Pagination;
use yii;

class NoticeController extends BaseController
{

    public $modelClass = NoticeModel::class;
    /**
     * 首页
     *
     * @return string
     */
    public function actionIndex()
    {
        $data   = $this->modelClass::find();
        $pages  = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $this->pageSize]);
        $models = $data->offset($pages->offset)->orderBy('id desc')->limit($pages->limit)->all();
        return $this->render($this->action->id, [
            'models' => $models,
            'pages' => $pages
        ]);
    }
    /**
     * 公告编辑\添加
     * @return string
     */
    public function actionNotice_save()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', null);
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $model->created_at = date('Y-m-d H:i:s');
            $model->updated_at = date('Y-m-d H:i:s');
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->render($this->action->id, [
            'model' => $model,
        ]);
    }
    /**
     * 返回模型
     *
     * @param $id
     * @return \yii\db\ActiveRecord
     */
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || empty(($model = $this->modelClass::find()->where(['id' => $id])->one()))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
    //删除
    public function actionDestroy(){
        $id = Yii::$app->request->get('id');

        $model = NoticeModel::findOne($id);
        $model->delete()
            ? $this->redirect(['index'])
            : $this->message($this->getError($model), $this->redirect(['index']), 'error');
    }
}